package com.kucowka.struts.actions.chat;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kucowka.struts.actions.WelcomeUserAction;
import com.kucowka.struts.messages.MessageStore;
import com.opensymphony.xwork2.Action;

public class UserRegistrationAction implements ServletRequestAware {
	
	private Logger logger = LoggerFactory.getLogger(UserRegistrationAction.class);

	public  static final String USER_ID_KEY = "user_id";
	public  static final String LOGIN_ID_KEY = "login_id";
	
	private String login;
	private HttpServletRequest httpServletRequest;

	public void setLogin(String login) {
		this.login = login;
	}

	public String execute() {

		HttpSession session = httpServletRequest.getSession();
		
		if (session.getAttribute(USER_ID_KEY) == null) {
			String sessionUserId = UUID.randomUUID().toString();
			session.setAttribute(USER_ID_KEY, sessionUserId);
			session.setAttribute(LOGIN_ID_KEY, login);
			MessageStore.addAuthor(sessionUserId);
			
			logger.info("New user: " + login + " was registerd with user_id: " + sessionUserId);
		}
		
		return Action.SUCCESS;
	}

	@Override
	public void setServletRequest(HttpServletRequest httpServletRequest) {
		this.httpServletRequest = httpServletRequest;
	}
}
